/**
 * 贴图库管理器
 * 管理项目的贴图库，显示所有贴图和引用数据
 */

export class TextureLibraryManager {
    constructor(projectId) {
        this.projectId = projectId;
        this.textures = [];
        this.container = null;
        this.initialized = false;
    }
    
    /**
     * 初始化贴图库界面
     */
    async initialize() {
        if (this.initialized) {
            // 已初始化，只刷新列表
            await this.loadTextures();
            return;
        }
        
        console.log('🎨 初始化贴图库...');
        
        this.container = document.getElementById('texture-library-list');
        
        if (!this.container) {
            console.error('❌ 未找到贴图库容器元素');
            return;
        }
        
        // 绑定上传按钮
        this.bindUploadButton();
        
        // 绑定搜索功能
        this.bindSearchInput();
        
        // 加载贴图列表
        await this.loadTextures();
        
        this.initialized = true;
        console.log('✅ 贴图库初始化完成');
    }
    
    /**
     * 加载贴图库
     */
    async loadTextures() {
        try {
            const response = await fetch(`/api/projects/${this.projectId}/textures`);
            const result = await response.json();
            
            if (result.success) {
                this.textures = result.data || [];
                this.renderTextureList();
                return this.textures;
            } else {
                console.warn('⚠️ 加载贴图库失败:', result.error);
                this.textures = [];
                this.renderTextureList();
                return [];
            }
        } catch (error) {
            console.warn('⚠️ 加载贴图库失败:', error);
            this.textures = [];
            this.renderTextureList();
            return [];
        }
    }
    
    /**
     * 渲染贴图列表
     */
    renderTextureList() {
        if (!this.container) {
            console.error('❌ 贴图库容器不存在');
            return;
        }
        
        // 清空容器
        this.container.innerHTML = '';
        
        if (this.textures.length === 0) {
            this.container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">🖼️</div>
                    <div class="empty-text">暂无贴图</div>
                    <div class="empty-hint">上传贴图后将在此显示</div>
                </div>
            `;
            this.updateStats();
            return;
        }
        
        // 按名称排序
        const sortedTextures = [...this.textures].sort((a, b) => {
            const nameA = (a.displayName || a.name || '').toLowerCase();
            const nameB = (b.displayName || b.name || '').toLowerCase();
            return nameA.localeCompare(nameB);
        });
        
        // 渲染每个贴图
        sortedTextures.forEach(texture => {
            const textureItem = this.createTextureItem(texture);
            this.container.appendChild(textureItem);
        });
        
        // 更新统计数据
        this.updateStats();
        
        console.log(`✅ 已渲染 ${this.textures.length} 个贴图`);
    }
    
    /**
     * 更新统计数据
     */
    updateStats() {
        const totalCount = this.textures.length;
        const usedCount = this.textures.filter(t => (t.referenceCount || 0) > 0).length;
        const unusedCount = totalCount - usedCount;
        
        const totalEl = document.getElementById('texture-total-count');
        const usedEl = document.getElementById('texture-used-count');
        const unusedEl = document.getElementById('texture-unused-count');
        
        if (totalEl) totalEl.textContent = totalCount;
        if (usedEl) usedEl.textContent = usedCount;
        if (unusedEl) unusedEl.textContent = unusedCount;
    }
    
    /**
     * 创建贴图列表项 - 卡片式布局
     */
    createTextureItem(texture) {
        const item = document.createElement('div');
        item.className = 'texture-library-item';
        item.dataset.textureId = texture.id;
        
        // 贴图预览（包含图片和引用数徽章）
        const preview = document.createElement('div');
        preview.className = 'texture-preview';
        
        const img = document.createElement('img');
        // 使用API路径访问贴图文件（与材质编辑器一致）
        const backendUrl = window.APP_CONFIG?.backendUrl || window.location.origin;
        img.src = `${backendUrl}/api/projects/${this.projectId}/textures/${texture.id}/file`;
        img.alt = texture.displayName || texture.name;
        img.loading = 'lazy';
        img.onerror = () => {
            img.src = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="100" height="100"%3E%3Crect fill="%23333" width="100" height="100"/%3E%3Ctext x="50%25" y="50%25" text-anchor="middle" dy=".3em" fill="%23999" font-size="12"%3E加载失败%3C/text%3E%3C/svg%3E';
        };
        preview.appendChild(img);
        
        // 引用数徽章
        const refCount = texture.referenceCount || 0;
        const badge = document.createElement('div');
        badge.className = `texture-ref-badge ${refCount === 0 ? 'ref-zero' : ''}`;
        badge.innerHTML = `<span>📌</span><span>${refCount}</span>`;
        badge.title = refCount === 0 ? '未被引用' : `被 ${refCount} 个材质引用`;
        preview.appendChild(badge);
        
        // 贴图信息
        const info = document.createElement('div');
        info.className = 'texture-info';
        
        const name = document.createElement('div');
        name.className = 'texture-name';
        name.textContent = texture.displayName || texture.name;
        name.title = texture.displayName || texture.name;
        
        const details = document.createElement('div');
        details.className = 'texture-details';
        
        // 图片尺寸
        const dimensionText = (texture.width && texture.height) 
            ? `📐 ${texture.width} × ${texture.height}` 
            : '📐 尺寸未知';
        
        // 文件大小
        const sizeText = `💾 ${this.formatFileSize(texture.size)}`;
        
        // 引用数量
        const refText = refCount === 0 
            ? '🔗 未被引用' 
            : `🔗 ${refCount} 个材质`;
        
        details.innerHTML = `
            <div class="texture-dimension">${dimensionText}</div>
            <div class="texture-size">${sizeText}</div>
            <div class="texture-reference ${refCount === 0 ? 'ref-zero' : ''}">${refText}</div>
        `;
        
        info.appendChild(name);
        info.appendChild(details);
        
        // 操作按钮
        const actions = document.createElement('div');
        actions.className = 'texture-actions';
        
        // 查看大图按钮（总是显示）
        const viewBtn = document.createElement('button');
        viewBtn.className = 'texture-action-btn view-btn';
        viewBtn.innerHTML = '👁️ 查看';
        viewBtn.title = '查看大图';
        viewBtn.onclick = (e) => {
            e.stopPropagation();
            this.showTexturePreview(texture);
        };
        actions.appendChild(viewBtn);
        
        // 删除按钮已移除 - 不允许删除贴图
        
        item.appendChild(preview);
        item.appendChild(info);
        item.appendChild(actions);
        
        // 点击卡片查看大图
        item.onclick = () => {
            this.showTexturePreview(texture);
        };
        
        return item;
    }
    
    /**
     * 显示贴图引用详情
     */
    async showTextureReferences(texture) {
        const refCount = texture.referenceCount || 0;
        const referencedBy = texture.referencedBy || [];
        
        if (refCount === 0) {
            alert('该贴图未被任何材质引用');
            return;
        }
        
        // 使用API路径访问贴图文件（与材质编辑器一致）
        const backendUrl = window.APP_CONFIG?.backendUrl || window.location.origin;
        const textureUrl = `${backendUrl}/api/projects/${this.projectId}/textures/${texture.id}/file`;
        
        // 创建引用列表对话框
        const dialog = document.createElement('div');
        dialog.className = 'texture-ref-dialog';
        dialog.innerHTML = `
            <div class="texture-ref-dialog-content">
                <div class="texture-ref-dialog-header">
                    <h3>贴图引用详情</h3>
                    <button class="close-btn">✕</button>
                </div>
                <div class="texture-ref-dialog-body">
                    <div class="texture-ref-info">
                        <div class="texture-ref-preview">
                            <img src="${textureUrl}" alt="${texture.displayName || texture.name}">
                        </div>
                        <div class="texture-ref-details">
                            <div class="texture-ref-name">${texture.displayName || texture.name}</div>
                            <div class="texture-ref-count">被 ${refCount} 个材质引用</div>
                        </div>
                    </div>
                    <div class="texture-ref-list">
                        <h4>引用的材质：</h4>
                        <ul>
                            ${referencedBy.map(matId => `<li>${matId}</li>`).join('')}
                        </ul>
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(dialog);
        
        // 关闭按钮
        dialog.querySelector('.close-btn').onclick = () => {
            dialog.remove();
        };
        
        // 点击背景关闭
        dialog.onclick = (e) => {
            if (e.target === dialog) {
                dialog.remove();
            }
        };
    }
    
    /**
     * 显示贴图预览（放大查看）- 包含引用材质列表
     */
    showTexturePreview(texture) {
        const refCount = texture.referenceCount || 0;
        const referencedBy = texture.referencedBy || [];
        
        const dialog = document.createElement('div');
        dialog.className = 'texture-preview-dialog';
        
        // 使用API路径访问贴图文件（与材质编辑器一致）
        const backendUrl = window.APP_CONFIG?.backendUrl || window.location.origin;
        const textureUrl = `${backendUrl}/api/projects/${this.projectId}/textures/${texture.id}/file`;
        
        // 构建引用材质列表HTML
        let referencesHTML = '';
        if (refCount > 0 && referencedBy.length > 0) {
            referencesHTML = `
                <div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255, 255, 255, 0.1);">
                    <div style="font-size: 12px; color: #6c9; margin-bottom: 8px;">
                        📌 被 ${refCount} 个材质引用：
                    </div>
                    <div style="display: flex; flex-wrap: wrap; gap: 6px;">
                        ${referencedBy.map(matId => `
                            <span style="
                                padding: 4px 10px;
                                background: rgba(108, 204, 153, 0.15);
                                border: 1px solid rgba(108, 204, 153, 0.3);
                                border-radius: 4px;
                                font-size: 11px;
                                color: #6c9;
                                font-family: monospace;
                            ">${matId}</span>
                        `).join('')}
                    </div>
                </div>
            `;
        } else {
            referencesHTML = `
                <div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255, 255, 255, 0.1);">
                    <div style="font-size: 12px; color: #888;">
                        🔗 未被任何材质引用
                    </div>
                </div>
            `;
        }
        
        dialog.innerHTML = `
            <div class="texture-preview-dialog-content">
                <div class="texture-preview-dialog-header">
                    <h3>🖼️ ${texture.displayName || texture.name}</h3>
                    <button class="close-btn">✕</button>
                </div>
                <div class="texture-preview-dialog-body">
                    <img src="${textureUrl}" alt="${texture.displayName || texture.name}">
                </div>
                <div class="texture-preview-dialog-footer" style="flex-direction: column; align-items: stretch;">
                    <div style="display: flex; gap: 20px;">
                        ${texture.width && texture.height ? 
                            `<div>📐 尺寸: ${texture.width} × ${texture.height}</div>` : 
                            '<div>📐 尺寸: 未知</div>'
                        }
                        <div>💾 大小: ${this.formatFileSize(texture.size)}</div>
                        <div>📄 格式: ${texture.ext}</div>
                    </div>
                    ${referencesHTML}
                </div>
            </div>
        `;
        
        document.body.appendChild(dialog);
        
        // 关闭按钮
        dialog.querySelector('.close-btn').onclick = () => {
            dialog.remove();
        };
        
        // 点击背景关闭
        dialog.onclick = (e) => {
            if (e.target === dialog) {
                dialog.remove();
            }
        };
        
        // ESC键关闭
        const handleEsc = (e) => {
            if (e.key === 'Escape') {
                dialog.remove();
                document.removeEventListener('keydown', handleEsc);
            }
        };
        document.addEventListener('keydown', handleEsc);
    }
    
    /**
     * 删除贴图
     */
    async deleteTexture(texture) {
        if (texture.referenceCount > 0) {
            alert('该贴图正被材质引用，无法删除');
            return;
        }
        
        const confirmed = confirm(`确定要删除贴图 "${texture.displayName || texture.name}" 吗？此操作无法撤销。`);
        
        if (!confirmed) {
            return;
        }
        
        try {
            const response = await fetch(`/api/projects/${this.projectId}/textures/${texture.id}`, {
                method: 'DELETE'
            });
            
            const result = await response.json();
            
            if (result.success) {
                console.log(`✅ 贴图删除成功: ${texture.displayName || texture.name}`);
                // 重新加载列表
                await this.loadTextures();
            } else {
                alert(`删除失败: ${result.error}`);
            }
        } catch (error) {
            console.error('❌ 删除贴图失败:', error);
            alert(`删除失败: ${error.message}`);
        }
    }
    
    /**
     * 格式化文件大小
     */
    formatFileSize(bytes) {
        if (!bytes) return '0 B';
        
        const units = ['B', 'KB', 'MB', 'GB'];
        let size = bytes;
        let unitIndex = 0;
        
        while (size >= 1024 && unitIndex < units.length - 1) {
            size /= 1024;
            unitIndex++;
        }
        
        return `${size.toFixed(unitIndex === 0 ? 0 : 1)} ${units[unitIndex]}`;
    }
    
    /**
     * 获取贴图详情
     */
    async getTexture(textureId) {
        try {
            const response = await fetch(`/api/projects/${this.projectId}/textures/${textureId}`);
            const result = await response.json();
            
            if (result.success) {
                return result.data;
            } else {
                throw new Error(result.error || '获取失败');
            }
        } catch (error) {
            console.error('❌ 获取贴图失败:', error);
            throw error;
        }
    }
    
    /**
     * 绑定上传按钮
     */
    bindUploadButton() {
        const uploadBtn = document.getElementById('upload-texture-btn');
        if (!uploadBtn) return;
        
        uploadBtn.addEventListener('click', () => {
            this.uploadTexture();
        });
    }
    
    /**
     * 上传贴图
     */
    uploadTexture() {
        // 创建文件输入
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        input.multiple = true; // 允许多选
        
        input.onchange = async (e) => {
            const files = Array.from(e.target.files);
            if (files.length === 0) return;
            
            try {
                console.log(`📤 [贴图上传] 开始上传 ${files.length} 个文件...`);
                
                // 📋 第一步：上传前检查所有文件是否有同名
                const duplicateFiles = [];
                const validFiles = [];
                
                for (const file of files) {
                    if (this.checkDuplicateTextureName(file.name)) {
                        duplicateFiles.push(file.name);
                    } else {
                        validFiles.push(file);
                    }
                }
                
                // 如果有重名文件，提示用户
                if (duplicateFiles.length > 0) {
                    const dupListShort = duplicateFiles.slice(0, 3);
                    const dupMore = duplicateFiles.length > 3 ? `等${duplicateFiles.length}个文件` : duplicateFiles.join('、');
                    
                    if (window.showManageMessage) {
                        window.showManageMessage(`检测到重名文件: ${dupMore}`, 'warning');
                    }
                    console.warn('⚠️ 检测到重名文件:\n' + duplicateFiles.map(f => `  - ${f}`).join('\n'));
                    
                    // 如果所有文件都重名，直接返回
                    if (validFiles.length === 0) {
                        if (window.showManageMessage) {
                            window.showManageMessage(`所有文件都已存在，无法上传。详情请查看控制台`, 'error');
                        }
                        return;
                    }
                    
                    // 部分重名，自动跳过重名文件，继续上传其他文件
                    console.log(`ℹ️ 将跳过重名文件，继续上传其他 ${validFiles.length} 个文件`);
                }
                
                let successCount = 0;
                let failCount = 0;
                const failedFiles = [];
                
                // 只上传非重名文件
                for (const file of validFiles) {
                    try {
                        await this.uploadSingleTexture(file);
                        successCount++;
                    } catch (error) {
                        console.error(`❌ 上传失败: ${file.name}`, error);
                        // 明确标记失败原因
                        const errorMsg = error.message || '上传失败';
                        failedFiles.push(`${file.name} - ${errorMsg}`);
                        failCount++;
                    }
                }
                
                // 重新加载贴图列表
                await this.loadTextures();
                
                // 显示结果
                const skippedCount = duplicateFiles.length;
                
                if (failCount === 0 && skippedCount === 0) {
                    // 全部成功
                    if (window.showManageMessage) {
                        window.showManageMessage(`成功上传 ${successCount} 个贴图`, 'success');
                    }
                    console.log(`✅ 成功上传 ${successCount} 个贴图`);
                } else if (successCount > 0 || skippedCount > 0 || failCount > 0) {
                    // 有任何需要显示的结果
                    if (skippedCount > 0 || failCount > 0) {
                        // 显示详细结果弹窗
                        this.showUploadResultDialog({
                            successCount,
                            failedFiles,
                            duplicateFiles
                        });
                    }
                    
                    // 简短toast提示
                    const summary = [];
                    if (successCount > 0) summary.push(`成功 ${successCount} 个`);
                    if (skippedCount > 0) summary.push(`重名跳过 ${skippedCount} 个`);
                    if (failCount > 0) summary.push(`失败 ${failCount} 个`);
                    
                    if (window.showManageMessage) {
                        const msgType = failCount > 0 ? 'error' : (skippedCount > 0 ? 'warning' : 'success');
                        window.showManageMessage(`上传完成: ${summary.join('，')}`, msgType);
                    }
                    
                    // 控制台日志
                    let detailLog = `⚠️ 上传完成:\n`;
                    if (successCount > 0) detailLog += `✅ 成功: ${successCount} 个\n`;
                    if (skippedCount > 0) {
                        detailLog += `⚠️ 重名跳过: ${skippedCount} 个\n${duplicateFiles.map(f => `   - ${f}`).join('\n')}\n`;
                    }
                    if (failCount > 0) {
                        detailLog += `❌ 失败: ${failCount} 个\n${failedFiles.map(f => `   - ${f}`).join('\n')}\n`;
                    }
                    console.warn(detailLog);
                }
                
            } catch (error) {
                console.error('❌ 上传贴图失败:', error);
                if (window.showManageMessage) {
                    window.showManageMessage('上传失败: ' + error.message, 'error');
                }
            }
        };
        
        input.click();
    }
    
    /**
     * 检查贴图名称是否重复
     */
    checkDuplicateTextureName(fileName) {
        return this.textures.some(texture => {
            const existingName = texture.displayName || texture.name || '';
            return existingName === fileName;
        });
    }
    
    /**
     * 显示上传结果弹窗
     */
    showUploadResultDialog(data) {
        const { successCount, failedFiles, duplicateFiles } = data;
        const failCount = failedFiles.length;
        const skippedCount = duplicateFiles.length;
        
        // 创建弹窗
        const dialog = document.createElement('div');
        dialog.className = 'upload-result-dialog-overlay';
        
        // 构建内容
        let content = `
            <div class="upload-result-dialog">
                <div class="upload-result-header">
                    <h3>📊 上传结果</h3>
                    <button class="upload-result-close">✕</button>
                </div>
                <div class="upload-result-body">
                    <div class="upload-result-summary">
                        ${successCount > 0 ? `<div class="result-item success"><span class="icon">✅</span><span>成功: ${successCount} 个</span></div>` : ''}
                        ${skippedCount > 0 ? `<div class="result-item warning"><span class="icon">⚠️</span><span>重名跳过: ${skippedCount} 个</span></div>` : ''}
                        ${failCount > 0 ? `<div class="result-item error"><span class="icon">❌</span><span>失败: ${failCount} 个</span></div>` : ''}
                    </div>
        `;
        
        // 重名文件列表
        if (skippedCount > 0) {
            content += `
                <div class="upload-result-section">
                    <h4>⚠️ 重名跳过的文件 (${skippedCount})</h4>
                    <div class="file-list warning-list">
                        ${duplicateFiles.map(file => `
                            <div class="file-item">
                                <div class="file-item-icon">📄</div>
                                <div class="file-item-content">
                                    <div class="file-item-name">${file}</div>
                                    <div class="file-item-reason warning-reason">文件已存在，无法上传</div>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            `;
        }
        
        // 失败文件列表
        if (failCount > 0) {
            content += `
                <div class="upload-result-section">
                    <h4>❌ 失败的文件 (${failCount})</h4>
                    <div class="file-list error-list">
                        ${failedFiles.map(fileInfo => {
                            const parts = fileInfo.split(' - ');
                            const fileName = parts[0];
                            const reason = parts[1] || '未知错误';
                            return `
                                <div class="file-item">
                                    <div class="file-item-icon">📄</div>
                                    <div class="file-item-content">
                                        <div class="file-item-name">${fileName}</div>
                                        <div class="file-item-reason error-reason">${reason}</div>
                                    </div>
                                </div>
                            `;
                        }).join('')}
                    </div>
                </div>
            `;
        }
        
        content += `
                </div>
                <div class="upload-result-footer">
                    <button class="btn-confirm">确定</button>
                </div>
            </div>
        `;
        
        dialog.innerHTML = content;
        document.body.appendChild(dialog);
        
        // 绑定关闭事件
        const closeDialog = () => dialog.remove();
        dialog.querySelector('.upload-result-close').addEventListener('click', closeDialog);
        dialog.querySelector('.btn-confirm').addEventListener('click', closeDialog);
        dialog.addEventListener('click', (e) => {
            if (e.target === dialog) closeDialog();
        });
    }
    
    /**
     * 上传单个贴图
     */
    async uploadSingleTexture(file) {
        const formData = new FormData();
        formData.append('texture', file);
        formData.append('originalFileName', file.name);
        
        const response = await fetch(`/api/projects/${this.projectId}/textures/upload`, {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || '上传失败');
        }
        
        console.log(`✅ 上传成功: ${file.name}`);
        
        // 添加到本地列表（不需要移除旧贴图，因为后端已经拒绝重名上传）
        if (result.data) {
            this.textures.push(result.data);
        }
        
        return result.data;
    }
    
    /**
     * 绑定搜索功能
     */
    bindSearchInput() {
        const searchInput = document.getElementById('texture-library-search-input');
        const clearBtn = document.getElementById('texture-library-search-clear');
        
        if (!searchInput) return;
        
        searchInput.addEventListener('input', (e) => {
            const keyword = e.target.value.toLowerCase().trim();
            
            // 显示/隐藏清除按钮
            if (clearBtn) {
                clearBtn.style.display = keyword ? 'block' : 'none';
            }
            
            // 过滤贴图
            this.filterTextures(keyword);
        });
        
        // 清除按钮
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                searchInput.value = '';
                clearBtn.style.display = 'none';
                this.filterTextures('');
            });
        }
    }
    
    /**
     * 过滤贴图
     */
    filterTextures(keyword) {
        if (!this.textures || this.textures.length === 0) {
            this.renderTextureList();
            return;
        }
        
        if (!keyword) {
            // 没有搜索词，显示全部
            this.renderTextureList();
            return;
        }
        
        // 过滤贴图
        const filteredTextures = this.textures.filter(texture => {
            const name = (texture.displayName || texture.name || '').toLowerCase();
            return name.includes(keyword);
        });
        
        // 渲染过滤后的列表
        this.renderFilteredList(filteredTextures, keyword);
    }
    
    /**
     * 渲染过滤后的列表
     */
    renderFilteredList(textures, keyword) {
        if (!this.container) {
            console.error('❌ 贴图库容器不存在');
            return;
        }
        
        // 清空容器
        this.container.innerHTML = '';
        
        if (textures.length === 0) {
            this.container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">🔍</div>
                    <div class="empty-text">未找到匹配的贴图</div>
                    <div class="empty-hint">搜索关键词: "${keyword}"</div>
                </div>
            `;
            this.updateStats(); // 统计数据保持原样
            return;
        }
        
        // 按名称排序
        const sortedTextures = [...textures].sort((a, b) => {
            const nameA = (a.displayName || a.name || '').toLowerCase();
            const nameB = (b.displayName || b.name || '').toLowerCase();
            return nameA.localeCompare(nameB);
        });
        
        // 渲染每个贴图
        sortedTextures.forEach(texture => {
            const textureItem = this.createTextureItem(texture);
            this.container.appendChild(textureItem);
        });
        
        console.log(`🔍 筛选结果: ${textures.length}/${this.textures.length} 个贴图`);
    }
}

// 导出单例
let textureLibraryManagerInstance = null;

export function getTextureLibraryManager(projectId) {
    if (!textureLibraryManagerInstance || textureLibraryManagerInstance.projectId !== projectId) {
        textureLibraryManagerInstance = new TextureLibraryManager(projectId);
    }
    return textureLibraryManagerInstance;
}

/**
 * 卸载贴图库管理器
 */
export function unloadTextureLibraryManager() {
    if (textureLibraryManagerInstance) {
        textureLibraryManagerInstance.textures = [];
        textureLibraryManagerInstance.initialized = false;
        textureLibraryManagerInstance = null;
        window.textureLibraryManager = null;
    }
}

// 暴露到全局
window.getTextureLibraryManager = getTextureLibraryManager;
window.unloadTextureLibraryManager = unloadTextureLibraryManager;

